const Koa = require('koa')
const Router = require('koa-router')

const app = new Koa()
let router = new Router()


//Koa 应用级中间件

app.use(async (ctx, next) => {
  console.log(new Date())
  await next()  //当前路由匹配完成以后继续向下匹配
})

router.get('/', async (ctx) => {
  ctx.body = '首页'
})
//路由级中间件
router.get('/news', async (ctx, next) => {
  console.log('这是新闻页')
  await next()
})

//错误处理
app.use(async (ctx, next) => {
  await next()
  if (ctx.status === 404) {
    ctx.status = 404
    ctx.body = '这是一个404页面'
  }
})


router.get('/news', async (ctx) => {
  ctx.body = '新闻页'
})

app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000, () => {
  console.log('服务启动成功')
})